package com.study.utils;

import javax.servlet.http.HttpServletRequest;

public class IpAddressUtil {
    // 定义常见的IP头字段作为常量
    private static final String X_FORWARDED_FOR = "x-forwarded-for";
    private static final String PROXY_CLIENT_IP = "Proxy-Client-IP";
    private static final String X_FORWARDED = "X-Forwarded";
    private static final String WL_PROXY_CLIENT_IP = "WL-Proxy-Client-IP";
    private static final String X_REAL_IP = "X-Real-IP";
    private static final String UNKNOWN = "unknown";
    private static final String LOCAL_IPV4 = "127.0.0.1";
    private static final String LOCAL_IPV6 = "0:0:0:0:0:0:0:1";

    /**
     * 获取客户端IP
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        if (request == null) {
            return UNKNOWN;
        }

        String ip = getFirstNonEmptyHeader(request, X_FORWARDED_FOR, PROXY_CLIENT_IP, X_FORWARDED, WL_PROXY_CLIENT_IP, X_REAL_IP);

        if (ip == null || ip.equals(UNKNOWN) || ip.equals(LOCAL_IPV6)) {
            ip = request.getRemoteAddr();
        }

        // 将IPv6的本地地址转换为IPv4的本地地址
        return ip.equals(LOCAL_IPV6) ? LOCAL_IPV4 : ip;
    }

    /**
     * 获取第一个非空非"unknown"的头信息
     * @param request
     * @param headers
     * @return
     */
    private static String getFirstNonEmptyHeader(HttpServletRequest request, String... headers) {
        for (String header : headers) {
            String value = request.getHeader(header);
            if (value != null && !value.isEmpty() && !UNKNOWN.equalsIgnoreCase(value)) {
                return value;
            }
        }
        return null;
    }
}
